package com.bckj.fastboot.core.web.repeat;

import com.bckj.fastboot.core.jackson.JsonUtils;
import com.bckj.fastboot.core.lang.model.ApiResponse;
import com.bckj.fastboot.core.util.WebUtils;
import com.bckj.fastboot.core.web.repeat.strategy.RepeatSubmitProvider;
import com.bckj.fastboot.core.web.repeat.strategy.RepeatSubmitStrategy;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

@RequiredArgsConstructor
public class RepeatSubmitInterceptor implements HandlerInterceptor {

    @Resource
    private RepeatSubmitProvider repeatSubmitProvider;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod handlerMethod) {
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null) {
                RepeatSubmitStrategy strategy = repeatSubmitProvider.getStrategy(annotation.type());
                if (strategy.isRepeatSubmit(request, annotation)) {
                    ApiResponse<?> resp = ApiResponse.failed(annotation.message());
                    WebUtils.renderString(response, JsonUtils.toJsonStr(resp));
                    return false;
                }
            }
        }
        return true;
    }
}